import {
		baseUrl
	} from '@/common/config.js'
const updateOfflineData = (screenId) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '更新数据中'
		})
		uni.request({
			url: baseUrl + '/yz/screen/getOfflineData?screenId=' + screenId,
			method: 'POST',
			success: (res) => {
				uni.hideLoading();
				const data = res.data
				if (data.code === 0) {
					uni.showToast({
						title: '数据更新成功'
					})
					console.log(res);
					saveOfflineData(res.data.data)
					resolve()
				} else {
					// 错误处理
					uni.showToast({
						title: data.msg
					})
					reject(res)
				}

			},
			fail: (err) => {
				uni.hideLoading();
				console.error(err)
				reject();
			}
		})
	})
}
const saveOfflineData = (data) => {
	uni.setStorage({
		key: 'offlineData',
		data
	})
}
export default {
	updateOfflineData,
	offlineData() {
		return uni.getStorageSync('offlineData') || {};
	},
	facility() {
		return this.offlineData().facility || {}
	},
	screen() {
		return this.offlineData().screen || {}
	},
	screenElementList() {
		return this.offlineData().screenElementList || []
	},
	settingMap() {
		try {
			const json = this.facility().settingMapJson;
			return JSON.parse(json);
		} catch (e) {
			console.warn(e)
			return {}
		}
	},
	screenSettingParam() {
		try {
			const json = this.screen().settingParam;
			return JSON.parse(json);
		} catch (e) {
			console.warn(e)
			return {}
		}
	},
	getSetting(key) {
		return this.settingMap()[key]
	},
	getScreenSetting(key) {
		return this.screenSettingParam()[key]
	},
	// 获取属性列表
	attributes() {
		let attributes = this.offlineData().attributes || []
		// 格式化属性, 将settingMap升级为自身属性
		attributes.forEach(attr => {
			attr.settingObj = {}
			try{
				attr.settingObj = JSON.parse(attr.settingMap) || {};
			}catch(e){
				console.warn(e)
			}
		})
		return attributes
	},
	// 获取某个属性
	getAttribute(key){
		const attributes = this.attributes()
		for(const attribute of attributes){
			if(key === attribute.attrKey){
				// 
				return attribute
			}
		}
		return null
	}
}